package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.xml.crypto.Data;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {


    @Transactional(rollbackFor = Exception.class)  // 事物异常回滚
    @Override
    public ResponseResult login(AdUserDto dto) {

        //1. 检查用户是否存在
        //参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "用户名或密码不能为空");
        }
        // 用户名查询用户信息
        LambdaQueryWrapper<AdUser> wrapper = Wrappers.lambdaQuery();
        AdUser user = getOne(wrapper
                .eq(AdUser::getName, dto.getName())
                .eq(AdUser::getStatus, AdminConstants.AD_USER_ISSTATUS));

        if (user == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "用户名不存在");
        }
        //2. 检查密码是否正确
        String password = user.getPassword(); // 数据库密码(加密)
        String salt = user.getSalt();

        String salt1 = dto.getPassword() + salt;

        String newPwd = DigestUtils.md5DigestAsHex(salt1.getBytes());

        if (!password.equals(newPwd)) {
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //3. 检查用户状态是否有效(已检查)

        //4. 修改最近登录时间
        user.setLoginTime(new Date());
        updateById(user);

        //5. 颁发token
        String token = AppJwtUtil.getToken(user.getId().longValue());

        // 用户信息返回 VO
        AdUserVO adUserVO = new AdUserVO();
        BeanUtils.copyProperties(user, adUserVO);// 属性拷贝

        //6. 返回结果(jwt)
        HashMap map = new HashMap<>();
        map.put("token", token);
        map.put("user", adUserVO);

        return ResponseResult.okResult(map);
    }

    @Override
    public ResponseResult register(AdUser user) {

        //1.参数校验
        if (StringUtils.isEmpty(user.getName()) || StringUtils.isEmpty(user.getPassword())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"用户名或密码不能为空");
        }
        // 业务处理
        // MD5（密码 + salt）
        String salt = RandomStringUtils.randomAlphanumeric(10);
        String psd = user.getPassword() + salt;

        String saltPsd = DigestUtils.md5DigestAsHex(psd.getBytes());
        user.setPassword(saltPsd);
        user.setSalt(salt);
        user.setStatus(9);
        user.setCreatedTime(new Date());
        this.save(user);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }
}